package cn.wolfcode.producer._02_mode;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;

/**
 * 异步的方式发送消息:不管返回的是发送成功还是失败都会继续发送
 * 结果是事件回调的方式,所以必须要求生产者在线
 */
public class Producer1 {
    public static void main(String[] args) throws Exception {
        //1.创建生产者对象
        DefaultMQProducer producer = new DefaultMQProducer("wolfcode_producer");
        //2.设置nameSrv地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        //3.启动生产者
        producer.start();
        //设置线程中,保持在线,给个100计数器
        CountDownLatch count = new CountDownLatch(100);
        //发送一百条消息
        for (int i=0; i < 100; i++) {
            //4.设置发送的消息(默认是同步消息)
            Message message = new Message("02_mode","你好啊rocketMQ".getBytes());
            //5.生产者对象发送消息
           producer.send(message, new SendCallback() {
               @Override
               public void onSuccess(SendResult sendResult) {
                   System.out.println("发送成功");
                   count.countDown();
               }
               @Override
               public void onException(Throwable throwable) {
                   System.out.println("发送失败");
                   count.countDown();
               }
           });
           //当都发送完的时候,在关闭连接
        }
        count.await();
        //6.关闭连接
        producer.shutdown();
    }
}
